package ph.com.gs3.formalistics.view.document.fields;

import java.util.List;

import ph.com.gs3.formalistics.global.utilities.logging.FLLogger;
import ph.com.gs3.formalistics.model.vo.business.form.FormFieldData;
import ph.com.gs3.formalistics.view.document.abstractfields.AbstractFieldView;
import android.content.Context;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class DropdownField extends AbstractFieldView {

	private FormFieldData formField;

	private Spinner spField;
	private List<String> options;

	public DropdownField(Context context, FormFieldData formField) {
		super(context, formField.getId());
		this.formField = formField;

		createLabeledDefaultContainer(formField.getLabel(), getFieldId() + "_container");

		createView();
	}

	private void createView() {

		spField = new Spinner(getContext());
		options = formField.getOptions();

		ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(getContext(),
		        android.R.layout.simple_spinner_item, options);

		spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spField.setAdapter(spinnerAdapter);
		setValue(formField.getValue());
		spField.setTag(formField.getId());
		spField.setEnabled(isEnabled);

		this.addView(spField);

	}

	@Override
	public void setEnabled(boolean isEnabled) {
		super.setEnabled(isEnabled);
		spField.setEnabled(isEnabled);
	}

	@Override
	public String getValue() {
		// TODO Auto-generated method stub
		return spField.getSelectedItem().toString();
	}

	@Override
	public void setValue(String value) {
		// Assign the value if this field is for viewing
		if (value != null && !"null".equals(value)) {
			if (options.indexOf(value) > -1) {
				spField.setSelection(options.indexOf(value));
			}
		}
	}

	@Override
	public void showError(String errorMessage) {
		FLLogger.e(TAG, "showError not yet implemented");
	}

	protected void initializeChangeListener() {
		spField.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				notifyValueChanged();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {}
		});
	}

}
